import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gameplay_flutter/lib_baseview/utils/cache_util.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';

import '../lib_basemodel/user/user.dart';
import '../lib_im/index.dart';
import '../lib_runtime/global_config.dart';
import '../lib_runtime/logger.dart';
import '../lib_user/user_manager.dart';
import '../m_chatroom/src/interface/root_proxy_model.dart';
import '../m_login/login_page_model.dart';
import '../m_login/os_login_page.dart';
import '../m_main/init_bindings.dart';
import '../m_main/main/main_page.dart';
import '../m_main/main_page_model.dart';
import '../m_main/splash_screen/main_init.dart';
import '../m_main/unread_message_count_model.dart';
import '../resource/language/generated/l10n.dart';
import 'app_navigator_observer.dart';
import 'global_notice/widgets/loading.dart';
import 'theme/jr.dart';
import 'utils/constant/text_styles.dart';
import 'utils/screen_utils.dart';

/// 全局监听
final appNavigatorObserver = AppNavigatorObserver();
final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();

class RootPage extends StatefulWidget {
  const RootPage({Key? key}) : super(key: key);

  @override
  State<RootPage> createState() => _RootPageState();
}

GlobalKey<NavigatorState> rootNavigatorState = GlobalKey<NavigatorState>();

class _RootPageState extends State<RootPage>
    with WidgetsBindingObserver, TickerProviderStateMixin {
  final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
  final GlobalKey<OverlayState> overlayKey = GlobalKey<OverlayState>();
  double weworkTextScaleFactor = 1.0;
  bool useSystemTextScaleFactor = true;
  StreamSubscription? _linkStream;
  bool loading = true;

  // late FirebaseAnalyticsObserver _firebaseAnalyticsObserver;

  @override
  void initState() {
    super.initState();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp, //只能纵向
      DeviceOrientation.portraitDown, //只能纵向
    ]);

    WidgetsBinding.instance.addObserver(this);
    ImManager.of.init();
    //AgManager.of.init();

    // _firebaseAnalyticsObserver = FirebaseAnalyticsObserver(analytics: FirebaseAnalytics.instance);

    // Future.delayed(const Duration(milliseconds: 1000)).then((dynamic val) {
    //   // if (Platform.isAndroid) FlutterCommon().createNotificationChannel();
    //   initUniLinks();
    //   initRoomPlugins();
    // });
    _launchLoading();
    // UniLinksService.init();

    String? locJson = CacheUtil.get(CacheKeys.userCacheKey);
    if (locJson.isNotEmpty) {
      User? user = User.fromJson(jsonDecode(locJson));
      if (user.token != null) {
        UserManager.instance.updateUserInfo(user);
      }
    }
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    ScreenUtils.ins.updateScreenWidth(
        MediaQueryData.fromWindow(WidgetsBinding.instance.window));
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    RLog.i("RootPage:didChangeAppLifecycleState");
    if (state == AppLifecycleState.resumed) {
      GlobalConfig.appLifecycleActive = true;
      RLog.i("RootPage:切换到了前台");
    } else if (state == AppLifecycleState.paused) {
      GlobalConfig.appLifecycleActive = false;
      RLog.i("RootPage:切换到了后台");
    }
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => UnreadMessageCountModel()),
        ChangeNotifierProvider(create: (_) {
          var mainModel = MainPageModel();
          mainModel.initGlobalAnimationController(this, context);
          return mainModel;
        }),
        ChangeNotifierProvider(create: (_) => RootProxyModel()),
        ChangeNotifierProvider(create: (_) => LoginPageModel()),
      ],
      child: ScreenUtilInit(
          designSize: const Size(375, 812),
          minTextAdapt: true,
          splitScreenMode: true,
          builder: (context, child) {
            return GetMaterialApp(
                builder: (BuildContext context, Widget? child) {
                  return DefaultTextStyle(
                    style: const TextStyle(
                        fontFamily: fontFamily,
                        fontFamilyFallback: [fontFamilyFallback]),
                    child: MediaQuery(
                        //设置文字大小不随系统设置改变
                        data: MediaQuery.of(context)
                            .copyWith(textScaleFactor: 1.0),
                        child: FlutterGlobalNotice(
                          child: FlutterEasyLoading(
                            child: StreamBuilder<ThemeStyle>(
                                stream: JR.subscribeThemeStyle,
                                builder: (context, snapshot) {
                                  return child!;
                                }),
                          ),
                        )),
                  );
                },
                theme: ThemeData(
                  brightness: Brightness.light,
                  splashColor: Colors.transparent,
                  highlightColor: Colors.transparent,
                ),
                title: "Yahabbi",
                locale: _getLocale(),
                navigatorKey: rootNavigatorState,
                initialBinding: InitialBinding(),
                navigatorObservers: [
                  appNavigatorObserver,
                  // _firebaseAnalyticsObserver,
                  routeObserver
                ],
                localeResolutionCallback: onLocaleResolutionCallback,
                localizationsDelegates: const <LocalizationsDelegate<dynamic>>[
                  T.delegate,
                  GlobalMaterialLocalizations.delegate,
                  GlobalWidgetsLocalizations.delegate,
                  GlobalCupertinoLocalizations.delegate,
                ],
                routes: {
                  // JrNavigator.NAVIGATOR_URL_WORKBENCH: (BuildContext context) =>
                  //     const WorkBenchMainPage(), //注册嘉宾工作台路由
                },
                supportedLocales: T.delegate.supportedLocales,
                home: _renderHome());
          }),
    );
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _linkStream?.cancel();
    super.dispose();
  }

  initUniLinks() async {
    // _linkStream = getLinksStream().listen((String? link) {
    //   RLog.d('getLinksStreamlink: $link $mounted');
    //   if (!mounted) return;
    //   if (link != null) {
    //     SchemeHelper.checkAndGo(context, link);
    //     resetLink();
    //   }
    // }, onError: (err) {
    //   if (!mounted) return;
    // });

    String? initialLink;
    try {
      // if (Platform.isAndroid) {
      //   initialLink = await getLatestLink();
      // } else {
      //   initialLink = await getInitialLink();
      // }
      RLog.d('initial link: $initialLink $mounted');
    } on PlatformException {
      RLog.d('Failed to get initial link.');
    } on FormatException {
      RLog.d('Failed to parse the initial link as Uri.');
    }

    if (!mounted) return;
    if (initialLink != null) {
      // SchemeHelper.checkAndGo(context, initialLink);
      // resetLink();
    }
  }

  initRoomPlugins() {
    // RoomManager.instance.addPlugin(SudRoomPlugin());
    // RoomManager.instance.addPlugin(CPRoomPlugin());
  }

  Locale? onLocaleResolutionCallback(
      Locale? locale, Iterable<Locale> supportedLocales) {
    return _getLocale();
  }

  Widget _renderHome() {
    if (loading) {
      return Container(
        alignment: AlignmentDirectional.center,
        child: const CupertinoActivityIndicator(),
      );
    }

    // String? locJson = CacheUtil.get(CacheKeys.userCacheKey);
    //
    // if (locJson.isNotEmpty) {
    //   User? user = User.fromJson(jsonDecode(locJson));
    //   if (user.token != null) {
    //     UserManager.instance.updateUserInfo(user);
    //     return MainPage();
    //   }
    // }
    //
    // return const OSLoginPage();

    return Obx(() {
      final isLogin = UserManager.instance.token?.isNotEmpty ?? false;
      print("isLogin = $isLogin");
      return isLogin ? MainPage(key: UniqueKey()) : const OSLoginPage();
    }
    );
  }

  _launchLoading() async {
    await MainInit.launchInit();
    loading = false;
    setState(() {});
  }

  Locale? _getLocale() {
    // 优先使用缓存的语言
    final cachedLangCode = CacheUtil.get(CacheKeys.languageCode);
    // final cachedCountryCode = CacheUtil.get(CacheKeys.countryCode);
    if (cachedLangCode.isNotEmpty) {
      return Locale(cachedLangCode);
    }

    // 其次使用 GetX 管理的语言
    if (Get.locale != null) return Get.locale;

    // 默认第一个支持的语言
    final supportedLocales = T.delegate.supportedLocales;
    if (supportedLocales.isNotEmpty) {
      return supportedLocales.first;
    }

    return null;
  }
}
